local MAX_ARG = 11

local function escape(s)
	return s:gsub(".", function (c)
		local n = string.byte(c)
		if n < 32 or n > 127 then
			return "\\"..n
		else
			return c 
		end
	end)
end

local function toliteral(value)
	local t, v = type(value)
	if t == "nil" then
		v = "nil"
	elseif t == "string" then
		v = '"'..escape(value)..'"'
	else
		v = tostring(value)
	end
	return v
end

local record
local function output_event(db, index, output)
	local event = db.events[index]
	if not record then
		if event == "VARIABLES_LOADED" then
			record = true
		end
	elseif event == "update" then
		output("\t{ type=\"update\", elapsed=\"%s\" },\n", db.args[db.offsets[index]])
--		record = false
	elseif event ~= "ADDON_LOADED" then
		local args
		do
			local start_arg = db.offsets[index]
			local stop_arg = (index == #db.offsets) and #db.args or (db.offsets[index + 1] - 1)
			if stop_arg >= start_arg then
				local tmp = {}
				for i = start_arg, stop_arg do
					tmp[#tmp + 1] = toliteral(db.args[i])
				end
				args = "params = {" .. table.concat(tmp, ", ") .. "}"
			end
		end
		output("\t{ type=\"event\", event=\"%s\", %s},\n", event, args or "")
	end
end

local HEADER =[[
config.LOGIN_SEQUENCE = {
]]

local dofile = function (filename)
	local f = io.open(filename, "rb")
	local loader = function ()
		local line = f:read()
		if line then
			local before, content, after = line:match("^([%s+]\")(.*)(\", -- %[%d+%].*)")
			if before and content and after then
				content = escape(content)
				return before..content..after
			end
		end
		return line
	end
	local data = assert(load(loader, filename))
	data()
end

local function report_db(output, db)
	for i = 1, #db.events do
		output_event(db, i, output)
	end
end

local function main()
	dofile("!!!Recorder.lua")
	local f = io.open("events.lua", "w")
	local output = function (...)
		f:write((string.format(...)))
	end
	output("config.LOGIN_SEQUENCE = {\n")
	report_db(output, RecorderDB)
	output("}\n")
	f:close()
end

main()
